package com.tcp1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class Server {
	private ServerSocket serverSocket;
	private List<PrintWriter> allOut;
	private ExecutorService threadPool;
	public static void main(String[] args) {
		Server server = new Server();
		server.start();

	}
	public Server(){
		try {
			serverSocket = new ServerSocket(8080);
			allOut = new ArrayList<PrintWriter>();
			threadPool = Executors.newFixedThreadPool(40);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void start(){
		while(true){

			try {
				System.out.println("等待客户端的连接...");
				//监听客户端的连接
				Socket socket = serverSocket.accept();
				System.out.println("客户端已经连接上了！");

				ClientHandler handler = new ClientHandler(socket);
				threadPool.execute(handler);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}



	}

	private synchronized void addOut(PrintWriter out){
		allOut.add(out);
	}
	/**
	 * 将给定输出流从共享集合删除
	 * @param out
	 */
	private synchronized void removeOut(PrintWriter out){
		allOut.remove(out);
	}
	/**
	 * 将消息转发给所有客户端
	 * @param message
	 */
	private synchronized void sendMessage(String message){
		for(PrintWriter o : allOut){
			o.println(message);
		}
	}

	//线程体，并发处理不同客户端信息的交互
	public class ClientHandler implements Runnable{
		private Socket socket;
		/**
		 * 添加构造方法
		 * @param socket
		 */
		public ClientHandler(Socket socket) {
			super();
			this.socket = socket;
		}

		@Override
		public void run() {
			PrintWriter pw = null;
			try {
				//将客户端的信息存入allOut集合
				OutputStream out = socket.getOutputStream();
				OutputStreamWriter osw = new OutputStreamWriter(out, "utf-8");
				pw = new PrintWriter(osw,true);
				addOut(pw);



				//获取socket的输入流
				InputStream in = socket.getInputStream();
				InputStreamReader isr = new InputStreamReader(in, "utf-8");
				BufferedReader bf = new BufferedReader(isr);

				String message = null;
				while((message=bf.readLine())!= null){
					sendMessage(message);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				removeOut(pw);
				if(socket!=null){
					try {
						socket.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}

	}


}
